
import nProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { createRouter, createWebHistory } from "vue-router";
import { staticRouter, asyncRouterMap, notFoundRouter } from './routers'
import _ from 'lodash'
import { GlobalStore } from "@/store";
import { UserStore } from "@/store/modules/system/user";
const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRouter],
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

router.addRoute(notFoundRouter)

/**
 * 判断用户是否有权限访问单个路由
 * route：访问的路由
 */
const hasPermission = (route) => {
  const userStore = UserStore();
  const permissionList = userStore.permissions
  if (permissionList[0] === 'all') {

    return true
  }
  if (route.meta && route.meta.code) {
    // 判断route的code值是否存在于permissionList
    return permissionList.includes(route.meta.code)
  }
  return true
}

/**
 * 筛选可访问的动态路由
 * routerMap：访问的动态列表
 */
const filterAsyncRouter = (routerMap) => {
  const accessedRouters = routerMap.filter((route) => {
    if (hasPermission(route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children)
      }
      return true
    }
    return false
  })
  return accessedRouters
}


export const generateRouter = () => {
  const RouterMap = _.cloneDeep(asyncRouterMap)

  return new Promise(resolve => {
    const validRouter = filterAsyncRouter(RouterMap)
    validRouter.forEach((item) => {
     
      router.addRoute(item)
    })
    resolve(true)
  })
}





// ----------------------- 路由加载前 -----------------------
router.beforeEach(async (to, from, next) => {
  nProgress.start()
  const globalStore = GlobalStore();
  // const token = globalStore.token
  await generateRouter()



  // 1.如果是访问登陆页，没有 token 直接放行，有 token 就在当前页
  if (to.path === '/login') {
    if (!globalStore.token) return next();
    else return next(from.fullPath);
  }

  // // 2.判断是否有 Token，没有重定向到 login
  if (!globalStore.token) return next('/login');

  // // 3正常
  next()

});
// ----------------------- 路由加载后 -----------------------
router.afterEach(() => {
  nProgress.done();
});


// ----------------------- 路由跳转错误后 -----------------------
router.onError(error => {
  nProgress.done();
  console.warn("路由错误", error.message);
});





export default router;
